package com.wushi.bigdata.executor;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @ClassName WebJobExecutor
 * @Deacription 通过ProcessBuilder执行命令
 * @Author wushumin
 * @Date 2021-10-11 15:43
 * @Version 1.0
 **/
@Slf4j
public class WebJobExecutor {
    /**
     * 执行shell命令，第一个为命令，其他为参数
     * @param cmd
     */
    public static void submitJob(String[] cmd){
//        ProcessBuilder command = new ProcessBuilder("C:\\Users\\wushumin.LCB\\AppData\\Local\\Programs\\Python\\Python36\\python.exe","-V");
//        ProcessBuilder command = new ProcessBuilder("CMD","/C","dir","d:\\");
        ProcessBuilder command = new ProcessBuilder(cmd);
        command.directory(new File("d:\\"));

        String os = System.getProperty("os.name").toLowerCase();
        log.info("======>os: {}",os);
        String charset = os.contains("windows")? "GB2312": "UTF-8";
        try {
            Process process = command.start();
            int result = process.waitFor();
            //需要指定编码

            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),charset));
            BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream(),charset));
            String line =null;
            while((line=in.readLine())!=null){

                log.info("======>{}",line);
            }
            while((line=err.readLine())!=null){
                log.error("======>{}",line);
            }
            log.info("======result:{}",result);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String cmd="/opt/app/flink-1.13.1/bin/sql-client.sh";
        String arg="-f";
        String script="/opt/app/flink-1.13.1/sql/impala-source-sink-sql.sql";
        WebJobExecutor.submitJob(new String[]{cmd,arg,script});
    }
}
